package net.quanter.shield.mybatis.typehandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Currency;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

/***
 *
 * created on 2021-03-12
 * @author 王老实
 *
 */
@MappedJdbcTypes({JdbcType.VARCHAR})
@MappedTypes({Currency.class})
public class CurrencyTypeHandler extends BaseTypeHandler<Currency> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Currency parameter, JdbcType jdbcType) throws SQLException {
        if (jdbcType == null) {
            ps.setString(i, parameter == null ? null : parameter.toString());
        } else {
            ps.setObject(i, parameter == null ? null : parameter.toString(), jdbcType.TYPE_CODE); // see r3589
        }
    }

    @Override
    public Currency getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String currency = rs.getString(columnName);
        return currency == null && rs.wasNull() ? null : Currency.getInstance(currency);
    }

    @Override
    public Currency getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String currency = rs.getString(columnIndex);
        return currency == null && rs.wasNull() ? null : Currency.getInstance(currency);
    }

    @Override
    public Currency getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String currency =cs.getString(columnIndex);
        return currency == null && cs.wasNull() ? null : Currency.getInstance(currency);
    }

}
